<?php
namespace Menory\SMS\Adapter\HuaXin;

use Menory\Standard\Sms\InterfaceAuth;

class Auth implements InterfaceAuth {

    /**
     * @var string
     */
    private $accessKey;

    /**
     * @var string
     */
    private $secretKey;

    /**
     * Auth constructor.
     * @param string $accessKey
     * @param string $secretKey
     */
    public function __construct($accessKey, $secretKey) {

        $this->accessKey = $accessKey;
        $this->secretKey = $secretKey;

    }

    /**
     * @param $request
     * @return string
     */
    function genSign($request) {

        if ($request["sign_method"] == "md5") {
            $sign = self::generateSignMd5($request, $this->secretKey);
        }
        else {
            $sign = self::generateSignHmac($request, $this->secretKey);
        }
        return $sign;

    }

    private static function generateSignMd5($params, $secretKey) {

        ksort($params);
        $stringToBeSigned = $secretKey;
        foreach ($params as $k => $v) {
            $stringToBeSigned .= "$k$v";
        }
        unset($k, $v);
        $stringToBeSigned .= $secretKey;

        return strtoupper(md5($stringToBeSigned));

    }

    private static function generateSignHmac($params, $secretKey) {

        ksort($params);
        $stringToBeSigned = "";
        foreach ($params as $k => $v) {
            $stringToBeSigned .= "$k$v";
        }
        unset($k, $v);

        return strtoupper(hash_hmac("md5", $stringToBeSigned, $secretKey));

    }

}